import smtplib
import os
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from config.config import Config
from common.consts import REPORT_PATH
from common.log import Log

c = Config()
logger = Log.get_logger()

def send_email(report):
    #创建邮件对象
    msg = MIMEMultipart()
    #配置email头
    msg['Subject'] = c.get_email('subject')
    msg['Form'] = c.get_email('user')
    msg['To'] = c.get_email('receiver')
    #格式化email正文，同时将报告以附件的形式发送
    with open(os.path.join(REPORT_PATH,report),'rb') as f:
        body = f.read()
        attach = MIMEBase('zip','zip',filename=report)
        #给附件重命名，一般和源文件一样
        attach.add_header('Content-Disposition','attachment',filename=('gb2312','',report))
        attach.set_payload(body)
        encoders.encode_base64(attach)
        msg.attach(attach)

    try:
        #连接smtp服务器，发送邮件
        smtp = smtplib.SMTP()
        smtp.connect(c.get_email("server"))
        smtp.login(c.get_email('user'),c.get_email('pwd'))
        smtp.sendmail(c.get_email('user'),c.get_email('receiver'),msg.as_string())
    except Exception as e:
        print(e)
        print('发送失败')
        logger.error('邮件发送失败，请检查邮件配置')
    else:
        print('发送成功')
        logger.info('邮件发送成功')
    finally:
        smtp.quit()

if __name__ == '__main__':
    from  common.consts import CASE_PATH
    import os
    xx = os.path.join(CASE_PATH,'test_login.py')
    send_email(xx)
